package com.zang.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.zang.server.utils.JwtTokenUtil;
import com.zang.server.mapper.AdminMapper;
import com.zang.server.mapper.AdminRoleMapper;
import com.zang.server.mapper.MenuMapper;
import com.zang.server.pojo.*;
import com.zang.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zang
 * @since 2021-12-28
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private AdminMapper adminMapper;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    /**
     * 登录之后返回token
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password,String code,HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code)||!captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入错误");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //这里要考虑我们前端传过来的是明文密码，我们这里判断的是加密的所有要这样判断
        //使用springsecurity提供的加密工具
        if (userDetails==null || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或者密码不正确");
        }
        if(!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员！");
        }
        //更新security登录对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //成功之后分配令牌
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return  RespBean.success("登录成功",tokenMap);
    }

    /**
     * 根据用户名获取用户
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username)
                .eq("enabled",true));
    }

    /**
     * 根据用户id查询角色列表
     * @param admin
     * @return
     */
    @Override
    public List<Role> getRoles(Integer admin) {
        return menuMapper.getRoles(admin);
    }

    /**
     * 获取所有操作员
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(((Admin)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId(),keywords);
    }

    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {

        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        Integer result = adminMapper.addAdminRole(adminId, rids);
        if (rids.length==result){
            return RespBean.success("更新成功!");
        }
        return RespBean.error("更新失败!");
    }

    @Override
    public boolean insertAdmin(AdminLoginParam adminLoginParam) {
        String ePassword = passwordEncoder.encode(adminLoginParam.getPassword());
        adminLoginParam.setPassword(ePassword);
        Integer i =  adminMapper.insertAdmin(adminLoginParam);
        if (i!=0){
            return true;
        }
        return false;

    }

    @Override
    public RespBean getAdminPassword(String oldPass, String pass, String adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
        if (encode.matches(oldPass,admin.getPassword())){
            admin.setPassword(encode.encode(pass));
            int i = adminMapper.updateById(admin);
            if (i==1){
                RespBean.success("更新成功");
            }
        }
        return RespBean.error("更新失败");
    }


}
